package com.spsoft.vatoutinv.service.flowprocess;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.ProcessParamBo;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.vatoutinv.entity.vmsmanualinvoice.VmsManualBase;
import com.spsoft.vatoutinv.service.vmsmanualinvoice.VmsManualBaseService;
import com.spsoft.workflow.common.enums.bus.ManualNodeEnums;
import com.spsoft.workflow.service.BusinessHandlerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 手动流程处理业务实现类，bean，取自BusFlowTypeEnums.FLOW_SGKP
 *
 * @author cdl
 * @date 2023/12/15
 */
@Service("FLOW_SGKP")
@Slf4j
@RequiredArgsConstructor
public class ManualProcessHandlerServiceImpl implements BusinessHandlerService {

    private final VmsManualBaseService vmsManualBaseService;

    @Override
    public void processHandler(ProcessParamBo pp) throws BusinessException {
        Long busId=pp.getBusId();
        String busDataJson=pp.getBusData();
        String nodeId=pp.getNodeId();

        ManualNodeEnums e = ManualNodeEnums.valueOfCode(nodeId);
        if (e == null) {
            throw new BusinessException(ResponseEnum.PARAM_VALIDATED_ERROR.getCode(), "审批流程有误，请联系管理员");
        }

        switch (e) {
            case ROOT:
            case FLOW_SGKP_SP:
                /**
                 * 校验是否有发票数据
                 */
                // 根据审批流id获取发票信息
                LambdaQueryWrapper<VmsManualBase> baseQueryWrapper = new LambdaQueryWrapper<>();
                baseQueryWrapper.eq(VmsManualBase::getApplyId, busId);
                List<VmsManualBase> list = vmsManualBaseService.list(baseQueryWrapper);
                if (CollectionUtil.isEmpty(list)) {
                    throw new BusinessException(ResponseEnum.INVOICE_NOT_FIND_ERROR);
                }
                break;
            case FLOW_SGKP_KP:
                /**
                 * 开票
                 */
                Result<Object> result = vmsManualBaseService.manualInvoice(busId, SecurityUtils.getTokenUser());
                if (!ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new BusinessException(result.getCode(), result.getMessage());
                }
                break;
            default:
                // 未知节点报错
                throw new BusinessException(ResponseEnum.PROCESS_NODE_ERROR);
        }
    }
}
